package com.atjava.nebula.core.exception.baseExp;

import java.io.PrintStream;
import java.text.MessageFormat;

import com.atjava.nebula.core.exception.bean.ExceptionInfo;
import com.atjava.nebula.core.exception.config.ExpMsgResoureConfig;
import com.atjava.nebula.core.exception.support.ExceptionUtil;
import com.atjava.nebula.core.exception.support.ExpHandlerFactory;

/**
 * unckecked异常,不考虑其异常后的跳转URL
 * 此异常的子类异常,可以捕获也可不捕获
 */
public class SystemException extends RuntimeException{
	private static final long serialVersionUID = -8747842186943891183L;

	protected String exceptionMessage; 
    protected String context ;
    protected String msgCode ;
    protected Object[] args ;

	public SystemException(String str) {
		super(str) ;
		exceptionMessage = str ;
	}
	
	public SystemException(Throwable th, String str) {
		super(str, th) ;
		exceptionMessage = str ;
	}

	public SystemException(String msgCode, Object[] args, String context) {
    	this.msgCode = msgCode ;
    	this.args = args ;
    	this.context = context ;
    } 
    

    public String toString() {
        String s = getClass().getName();
        return s + ": " + exceptionMessage;
    }

    /*
     * 得到异常的友好信息
     * 异常没有在xml配置时，出错
     */
    public String getMessage() {    	
    	if(exceptionMessage != null) {
    		return exceptionMessage ;
    	}
    	
    	if(msgCode == null) {
    		ExceptionInfo info = ExceptionUtil.getExceptionInfo(this) ;
    		if(info == null) {
    			return null ;
    		}
    		String _msgCode = info.getMessageCode() ;
    		msgCode = ExpMsgResoureConfig.getInstance().getMessage(_msgCode, context) ;
    	}
    	exceptionMessage = MessageFormat.format(msgCode, args) ;
        return exceptionMessage;
    }
    
    public void printStackTrace() {
		ExpHandlerFactory.getInstance().handleException(this) ;
	} 
    
    //出错时,隐式调用此方法
	@Override
	public void printStackTrace(PrintStream s) {
		this.printStackTrace() ;
	}
}
